<template>
    <div class="user-query-container">
        <!-- 搜索栏卡片 -->
        <el-card class="card-container search-card">
            <div class="search-inputs">
                <el-input v-model="searchUserName" placeholder="请输入用户姓名" class="search-input" />
                <el-input v-model="searchUserEmail" placeholder="请输入用户邮箱" class="search-input" />
            </div>
            <div class="button-group">
                <el-button type="primary" @click="handleSearchUser" class="search-button">搜索</el-button>
                <el-button type="default" @click="handleReset" class="reset-button">重置</el-button>
            </div>
        </el-card>

        <!-- 表格卡片 -->
        <el-card class="card-container table-card">
            <el-table :data="paginatedUserData" style="width: 100%;" class="custom-table rounded-table"
                :header-cell-style="{ backgroundColor: '#1890ff !important', color: '#fff !important', borderBottom: '2px solid white !important' }"
                row-class-name="table-row">
                <!-- 修改操作列标题 -->
                <!-- 修改用户姓名字段为username -->
                <el-table-column prop="username" label="用户姓名"></el-table-column>
                <!-- 移除重复的username列 -->
                <el-table-column prop="email" label="用户邮箱"></el-table-column>
                <el-table-column prop="phone" label="电话"></el-table-column>
                <el-table-column prop="province" label="省份"></el-table-column>
                <el-table-column prop="city" label="城市"></el-table-column>
                <el-table-column prop="town" label="乡镇"></el-table-column>
                <!-- 使用格式化后的权限文本 -->
                <el-table-column prop="identityText" label="用户身份"></el-table-column>
                <!-- 移除账号状态列（后端无对应字段） -->
                <el-table-column label="操作" width="300">
                    <template #default="scope">
                        <!-- 冻结按钮：红色，当账号已冻结(FROZEN)时禁用 -->
                        <el-button type="danger" class="operation-btn" @click="handleFreeze(scope.row)"
                            :disabled="scope.row.status === 'FROZEN'"
                            :class="{ 'disabled-btn': scope.row.status === 'FROZEN' }"
                            style="margin-right: 12px; width: 90px;">
                            冻结
                        </el-button>
                        <!-- 解冻按钮：绿色，当账号正常(NORMAL)时禁用 -->
                        <el-button type="success" class="operation-btn" @click="handleUnfreeze(scope.row)"
                            :disabled="scope.row.status === 'NORMAL'"
                            :class="{ 'disabled-btn': scope.row.status === 'NORMAL' }" style="width: 90px;">
                            解冻
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <ElConfigProvider :locale="zhCn">
                    <el-pagination v-model:current-page="userCurrentPage" v-model:page-size="userPageSize"
                        :total="userData.length" :page-sizes="[10]" layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleUserSizeChange" @current-change="handleUserCurrentChange" :prev-text="'上一页'"
                        :next-text="'下一页'" :page-sizes-text="'条/页'" :jumper-text="'前往'" />
                </ElConfigProvider>
            </div>
        </el-card>
    </div>
</template>

<style scoped>
/* 卡片容器基础样式 */
.card-container {
    width: 70%;
    margin: 0 auto 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 搜索卡片样式 */
.search-card {
    padding: 20px;
}

/* 表格卡片样式 */
.table-card {
    padding: 20px;
}

/* 搜索输入框容器 */
.search-inputs {
    display: flex;
    gap: 10px;
    width: 100%;
}

/* 搜索栏样式 */
.search-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    width: 70%;
    margin-left: auto;
    margin-right: auto;
}

::v-deep .search-container .el-input {
    width: 300px;
    /* 减小搜索框宽度 */
    margin-right: 10px;
}

.search-input {
    width: 300px;
    /* 将50%改为固定像素宽度 */
}

.button-group {
    display: flex;
    gap: 10px;
    justify-content: flex-start;
    margin-top: 15px;
    /* 添加顶部间距，确保按钮在第二行 */
}

.search-button,
.reset-button {
    padding: 0 20px;
}

/* 修改分页容器样式 */
.pagination-container {
    margin-top: 20px;
    text-align: center;
    position: static;
    bottom: auto;
    left: auto;
    transform: none;
    background-color: transparent;
    padding: 0;
    box-shadow: none;
}

.el-table .cell {
    text-align: center;
}

/* 操作按钮样式 */
.operation-btn {
    margin: 0 4px;
    padding: 5px 10px;
}

.disabled-btn {
    opacity: 0.6;
    cursor: not-allowed;
    /* 新增禁用状态样式，确保显示为灰色 */
    background-color: #e0e0e0 !important;
    border-color: #d0d0d0 !important;
    color: #888 !important;
}

.custom-table {
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #e8e8e8;
}

::v-deep .custom-table .el-table__header-wrapper th {
    background-color: #1890ff !important;
    color: #fff !important;
    border-bottom: 2px solid #fff !important;
}


::v-deep .custom-table .el-table__body-wrapper .el-table__row {
    transition: all 0.2s ease;
    position: relative;
}

/* 优化悬浮效果，防止内容溢出 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover {
    transform: scale(1.01);
    /* 略微减小缩放比例 */
    transform-origin: center left;
    /* 从左侧居中放大，减少右侧溢出 */
    background-color: #1890ff !important;
    color: #fff !important;
    font-size: 15px;
    z-index: 10;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    /* 添加内边距补偿，防止内容溢出 */
    padding: 0 5px;
}

/* 确保表格有足够宽度容纳放大后的内容 */
::v-deep .el-table__body {
    width: 100% !important;
}

::v-deep .custom-table .el-table__body-wrapper .el-table__row td {
    border-bottom: 1px solid #e8e8e8;
    background-color: transparent !important;
}


::v-deep .custom-table .el-table__inner-wrapper {
    border-radius: 8px;
}


::v-deep .custom-table .el-table__header {
    box-shadow: 0 2px 0 #fff;
}
</style>

<script>
import { ref, computed, onMounted } from 'vue';
import { ElInput, ElTable, ElTableColumn, ElPagination, ElConfigProvider } from 'element-plus';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';

export default {
    name: 'UserQuery',
    components: {
        ElInput, ElTable,
    },
    setup() {
        // 搜索相关
        const searchUserName = ref('');
        const searchUserEmail = ref('');
        const userData = ref([]); // 修改：从 [...originalUserData] 改为 []
        const allUserData = ref([]); // 新增：存储所有用户数据用于搜索

        // 分页相关 - 保留原有声明，无需修改
        const userCurrentPage = ref(1);
        const userPageSize = ref(10);

        // 添加权限格式化函数
        const formatPermission = (permission) => {
            const permissionMap = {
                'REGULAR_USER': '普通用户',
                'DEVICE_ADMINISTRATOR': '设备管理员',
                'REPAIR_USER': '维护人员',
                'SYSTEM_ADMINISTRATOR': '系统管理员'
            };
            return permissionMap[permission] || permission;
        };

        // 从后端获取用户数据
        const fetchUserData = async () => {
            try {
                const response = await request.get('/admin/getAllUser');
                if (response.code === 200) {
                    // 按响应示例添加userId映射，并保留所有返回字段
                    const formattedData = response.data.map(user => ({
                        ...user, // 保留userId等所有后端返回字段
                        identityText: formatPermission(user.permission),
                        // 根据后端字符串状态值添加状态文本
                        statusText: user.status === 'FROZEN' ? '冻结' : '正常'
                    }));
                    allUserData.value = formattedData;
                    userData.value = [...formattedData];
                } else {
                    ElMessage.error('获取用户数据失败: ' + response.msg); // 修改：使用msg字段
                }
            } catch (error) {
                ElMessage.error('网络错误，无法获取用户数据');
                console.error(error);
            }
        };

        // 在组件挂载时获取数据
        onMounted(fetchUserData);

        // 分页计算属性

        // 方法
        const handleSearchUser = () => {
            const name = searchUserName.value.toLowerCase();
            const email = searchUserEmail.value.toLowerCase();

            // 基于后端数据进行过滤
            userData.value = allUserData.value.filter(item => {
                const matchName = name ? item.username.toLowerCase().includes(name) : true;
                const matchEmail = email ? item.email.toLowerCase().includes(email) : true;
                return matchName && matchEmail;
            });
            userCurrentPage.value = 1; // 重置页码
        };

        // 添加重置按钮功能实现
        const handleReset = () => {
            searchUserName.value = '';
            searchUserEmail.value = '';
            // 重置后重新加载所有数据
            userData.value = [...allUserData.value];
            userCurrentPage.value = 1;
        };

        const handleFreezeChange = (row) => {
            console.log('更新账号冻结状态:', row);
            ElMessage.success('账号冻结状态已更新');
        };

        const handleUserSizeChange = (val) => {
            userPageSize.value = val;
        };

        const handleUserCurrentChange = (val) => {
            userCurrentPage.value = val;
        };

        // 添加状态文本计算属性
        const userDataWithStatus = computed(() => {
            return userData.value.map(user => ({
                ...user,
                statusText: user.status === 0 ? '冻结' : '未冻结'
            }));
        });

        // 添加分页计算属性（修复未定义错误）
        const paginatedUserData = computed(() => {
            const startIndex = (userCurrentPage.value - 1) * userPageSize.value;
            return userDataWithStatus.value.slice(startIndex, startIndex + userPageSize.value);
        });

        // 修改冻结方法状态判断
        const handleFreeze = async (row) => {
            const userIndex = userData.value.findIndex(u => u.userId === row.userId);
            if (userIndex === -1) return;
            const originalRow = userData.value[userIndex];

            // 状态为NORMAL时可执行冻结操作
            if (originalRow.status === 'NORMAL') {
                try {
                    const response = await request.post('/admin/freezeOrUnFreezeUser', {
                        userId: originalRow.userId,
                        status: 0  // 发送字符串状态值
                    });
                    if (response.code === 200) {
                        // 更新状态为冻结
                        userData.value[userIndex].status = 'FROZEN';
                        ElMessage.success('账号已成功冻结');
                    } else {
                        ElMessage.error('冻结失败: ' + response.msg);
                    }
                } catch (error) {
                    ElMessage.error('冻结失败：' + (error.response?.data?.msg || '网络错误'));
                }
            } else {
                ElMessageBox.alert('账号处于冻结状态', '提示', { confirmButtonText: '确定' });
            }
        };

        // 修改解冻方法状态判断
        const handleUnfreeze = async (row) => {
            const userIndex = userData.value.findIndex(u => u.userId === row.userId);
            if (userIndex === -1) return;
            const originalRow = userData.value[userIndex];

            // 状态为FROZEN时可执行解冻操作
            if (originalRow.status === 'FROZEN') {
                try {
                    const response = await request.post('/admin/freezeOrUnFreezeUser', {
                        userId: originalRow.userId,
                        status: 1 // 发送字符串状态值
                    });
                    if (response.code === 200) {
                        // 更新状态为正常
                        userData.value[userIndex].status = 'NORMAL';
                        ElMessage.success('账号已成功解冻');
                    } else {
                        ElMessage.error('解冻失败: ' + response.msg);
                    }
                } catch (error) {
                    ElMessage.error('解冻失败：' + (error.response?.data?.msg || '网络错误'));
                }
            } else {
                ElMessageBox.alert('账号处于正常状态', '提示', { confirmButtonText: '确定' });
            }
        };

        return {
            searchUserName,
            searchUserEmail,
            userData,
            paginatedUserData,
            userCurrentPage,
            userPageSize,
            handleSearchUser,
            handleFreezeChange,
            handleUserSizeChange,
            handleUserCurrentChange,
            zhCn,
            // 添加方法暴露
            handleFreeze,
            handleUnfreeze,
            handleReset // 添加这一行，暴露重置方法
        };
    }
}
</script>
